# -*- coding: utf-8 -*-
# 呼叫转移生产环境配置成预发布，因此需要读预发布数据同步到生产环境
# author yeyi
# date 2021-08-09

import xlwt
import xlrd
import pymongo
import csv
import bson
import time
import traceback
import requests
import json

def printt(s):
    #print(s)
    f = open('callForward.log', 'a+', encoding='utf-8')
    print(s,file=f)
    f.close()


printt('start: '+time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))

# alert mongo 数据库地址
#conn = pymongo.MongoClient("mongodb://mongouser:pretce%40guangqi@10.123.2.239:27017/?authSource=admin")
conn = pymongo.MongoClient("mongodb://mongouser:tce%40guangqi2019@10.123.18.13:27017/?authSource=admin")
db = conn['iov_vehicle_gateway']
table = db.callforward_record

rxls = xlwt.Workbook()  # 新建工作簿
rxls.add_sheet('Sheet1', cell_overwrite_ok=True)
rxls.add_sheet('Sheet')

# 结果输出文件
f1 = open('result.csv', 'w', encoding='utf-8')
csv_writer_1 = csv.writer(f1)
csv_writer_1.writerow(['vin', '紧急联系人电话', 'sim电话','执行错误日期','url','结果'])

errIp='119.23.106.216'
correctIp='14.23.81.203'

# 查找包含错误 ip
result = table.find({
    "url": {"$regex": errIp}
}).sort([("date",-1)])
results=list(result)
printt('size: '+str(len(results)))
for re in results:
    try:
        url = re['url']
        url = url.replace(errIp,correctIp)
        request=re['request']
        body = json.dumps(request)
        response = requests.request("POST", url, data=body.encode('utf-8'))
        jsStr = str(response.content, 'utf-8')
        js = json.loads(jsStr)
        if js['success']:
            pass
        else:
            printt('query err: '+str(re))

        line = [request['vin'], request['ice'][0]['phone'], request['cardNumber'],re['date'],url,jsStr]
        csv_writer_1.writerow(line)
    except:
        # 打印错误信息
        printt('for err: '+str(re))
        traceback.print_exc()

f1.close()

printt('end: '+time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))